package org.funtester.performance.books.chapter04.section3;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.funtester.performance.books.chapter03.section3.ThreadTask;
import org.funtester.performance.books.chapter04.section2.HttpClientTool;
import org.funtester.performance.books.chapter04.section2.HttpRequestTool;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 注册+抽奖接口测试多线程任务类
 */
public class RegisterAndLotteryThreadTask extends ThreadTask {

    /**
     * 全局 HttpClient 对象
     */
    public static CloseableHttpClient httpClient = HttpClientTool.getHttpClient();

    /**
     * 用于生成手机号计数器
     */
    public static AtomicInteger start = new AtomicInteger(0);

    /**
     * 手机号前缀
     */
    public static String phonePrefix = "100";

    /**
     * 注册成功计数器
     */
    public int successCount = 0;

    /**
     * 注册失败计数器
     */
    public int failCount = 0;

    /**
     * 抽奖成功计数器
     */
    public int lotterySuccessCount = 0;

    /**
     * 抽奖失败计数器
     */
    public int lotteryFailCount = 0;

    /**
     * 构造方法
     * @param totalNum
     */
    public RegisterAndLotteryThreadTask(int totalNum) {
        this.totalNum = totalNum;// 设置执行的总次数
        this.costTime = new ArrayList<>(totalNum);// 初始化耗时收集集合类容量
    }

    @Override
    public void before() {
        super.before();// 调用父类方法
        start.compareAndSet(0, (int) System.currentTimeMillis() % 100000000);// 设置计数器初始值
    }

    @Override
    public void test() {
        String username = RandomTool.getRandomString(8);// 随机生成用户名
        String password = RandomTool.getRandomString(8);// 随机生成密码
        String phone = phonePrefix + start.incrementAndGet();// 生成手机号
        JSONObject reponseJson = register(username, password, phone);// 调用注册接口
        if (reponseJson != null && reponseJson.getInteger("code") == 0) {// 判断注册是否成功
            successCount++;// 注册成功计数器加 1
            String token = reponseJson.getString("token");// 获取 token
            if (token != null && !token.isEmpty()) {// 判断 token 是否为空
                JSONObject lotteryResponseJson = lottery(1, token);// 调用抽奖接口
                if (lotteryResponseJson != null && lotteryResponseJson.getInteger("code") == 0) {// 判断抽奖是否成功
                    lotterySuccessCount++;// 抽奖成功计数器加 1
                } else {
                    lotteryFailCount++;// 抽奖失败计数器加 1
                }
            }
        } else {
            failCount++;// 注册失败计数器加 1
        }
    }

    /**
     * 用户注册
     * @param username 用户名
     * @param password 密码
     * @param phone    手机号
     * @return
     */
    public static JSONObject register(String username, String password, String phone) {
        String uri = "http://localhost:8080/register";// 注册接口地址
        JSONObject params = new JSONObject();// 构建请求参数
        params.put("username", username);// 设置用户名
        params.put("password", password);// 设置密码
        params.put("phone", phone);// 设置手机号
        params.put("info", "注册用户性能测试信息 Hello FunTester !" + System.currentTimeMillis());
        HttpPost httpPost = HttpRequestTool.getHttpPost(uri, params.toJSONString());// 构建 POST 请求
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {// 执行请求
            int statusCode = response.getStatusLine().getStatusCode();// 获取响应状态码
            JSONObject reponseJson = HttpRequestTool.parseReponseJson(response);// 解析响应 JSON
            if (statusCode == HttpStatus.SC_OK && reponseJson.getInteger("code") == 0) {// 判断响应状态码和响应code
                return reponseJson;// 注册成功,返回响应 JSON
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;// 注册失败,返回 null
    }

    /**
     * 抽奖
     * @param activityId 活动 ID,新用户注册id为 1
     * @return
     */
    public static JSONObject lottery(int activityId, String token) {
        String uri = "http://localhost:8080/activity/lottery";
        JSONObject params = new JSONObject();// 构建请求参数
        params.put("activityId", activityId);// 设置活动 ID
        HttpPost httpPost = HttpRequestTool.getHttpPost(uri, params.toJSONString());// 构建 POST 请求
        httpPost.setHeader("token", token);// 设置 token
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {// 执行请求
            int statusCode = response.getStatusLine().getStatusCode();// 获取响应状态码
            JSONObject reponseJson = HttpRequestTool.parseReponseJson(response);// 解析响应 JSON
            if (statusCode == HttpStatus.SC_OK && reponseJson.getInteger("code") == 0) {// 判断响应状态码和响应code
                return reponseJson;// 请求成功,返回响应 JSON
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;// 请求失败,返回 null
    }


}